<?php
namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ApiRequest;
use App\Models\Order;
use App\Models\Cart;
use App\Models\User;
use App\Models\UserAddress;
use App\Models\OrderProduct;
use App\Services\Wechat;
use App\Models\UserCoupon;
use App\Models\System;
use App\Repos\OrderRepo;
use DB,Log;
use EasyWeChat;
use function EasyWeChat\Kernel\Support\generate_sign;

class OrderController extends Controller
{
    
    public function index(ApiRequest $request)
    {
        $rs['status']       =  true;        
        $where['user_id']   = $request->user_id; 
        if($request->status) {
            $where['status'] = $request->status;
        }       
        $rs['data'] = OrderRepo::pages($where,10);
        return response()->json($rs);

    }

    public function add(ApiRequest $request)
    {
        $rs['status'] = true;        
        
        $data['user_id'] = $request->user_id;
        $cart_ids = explode(',', $request->cart_ids); 
        $carts = Cart::whereIn('id',$cart_ids)->get();
        $data['total_price']  = $carts->sum('subtotal')*100;
        $data['total_amount'] =  $data['total_price'];     
        $data['status']      = 1;
        $data['code']        = date('YmdHis');
        $data['remark'] = $request->remark;
        if($request->coupon_id) {
            $where['coupon_id'] = (int)$request->coupon_id;
            $where['user_id']   = $request->user_id;
            $where['is_used'] = 0;
            $uc = UserCoupon::where($where)->first();
            $user_coupon_money = 0;
            if($uc) {

                $user_coupon_money         = object_get($uc,'coupon.reduce')*100;
                $data['total_price']      -= $user_coupon_money;
                $data['user_coupon_money'] = $user_coupon_money;
                $data['user_coupon_id']    = $uc->id;
            }
           
            
            
        }
        
        if($request->agent_id) {
            $data['agent_id']    = (int)$request->agent_id;
            $data['agent_money'] = round($data['total_price']/1000,2);
        }
        
        // 地址
        if($request->address_id) {
            $address = UserAddress::find($request->address_id);
            $data['truename'] = $address->truename;
            $data['mobile']   = $address->mobile;
            $data['address']  = $address->city.' '.$address->address;
        }
        
        $data['form_id'] = $request->form_id;

        $order = Order::create($data);
        foreach ($carts as $k => $v) {
            $op['order_id']    = $order->id;
            $op['product_id']  = $v->product_id;
            $op['product_num'] = $v->num;
            $op['product_price'] = $v->price;
            $op['product_name']  = $v->product_name;
            $op['product_thumb'] = $v->product_thumb;
           
            $op['spec_values']     = $v->spec_values;
            $op['subtotal']    = $v->subtotal;

            OrderProduct::create($op);
        }
        // 支付成功之后才能删除
        Cart::whereIn('id',$cart_ids)->delete();  

        // 推送用户  

       

        Log::info('订单金额:'.$data['total_price']);
                
        //  只有金额大于0才会调用支付
        if($data['total_price']>0) {
            $unifyData['openid']       = $request->user->small_openid;
            $unifyData['total_price']  = $data['total_price'];
            $unifyData['code']         = $data['code'];
            $unifyData['order_id']     = $order->id;
            $rs['data'] =  self::wechatUnifyOrder($unifyData); 
            return response()->json($rs);

        }
    
        return response()->json($rs);
    }

    

    public function info(ApiRequest $request)
    {
        $rs['status'] = false;
        $where['code']    = $request->code;
        $where['user_id'] = $request->user_id;
        $order = Order::where($where)->first();
        if($order) {
            $rs['status'] = true;
            $rs['data']   = $order;
            $rs['msg']    = '订单错误';
            return response()->json($rs);
        }

        $rs['msg'] = '订单错误';
        return response()->json($rs);
    }

    public function complete(ApiRequest $request)
    {
        $rs['status'] = false;
        $where['code']    = $request->code;
        $where['user_id'] = $request->user_id;
        $order = Order::where($where)->first();
        if($order) {
            if($order->status==1) {
                $order->status = 100;
                $order->completed_at = date('Y-m-d H:i:s');
                $order->save();

                User::where(['id'=>$order->user_id])->decrement('money',$order->total_price);
                

                //推送用户
                // 推送
            
                if(object_get($order,'user.openid')){
                    $msg = $order->toArray();
                    $msg['openid'] = object_get($order,'user.openid');
                    $msg['time'] = date('Y-m-d H:i:s');
                    $msg['remark'] = '您的订单已完成,祝您用餐愉快';
                    $msg['url']  = config('app.url').'/diancan-h5/orderlist.html';
                    //Wechat::sendMsgTpl('order_complete',$msg);    
                }    
            }
            $rs['status'] = true;
            //return redirect('/diancan/shop/orders/show?code='.$order->code);
        }
        $rs['msg'] = '订单错误';
        return response()->json($rs);
    }


    // 用户评价
    public function comment(ApiRequest $request)
    {
        $rs['status']      = false;
        $data = $request->pure();  
        $flag = OrderRepo::comment($data);     
        if($flag['status'] == true) {
            $rs['status'] = true;
            $rs['msg'] = '操作成功';
            return response()->json($rs);
        }
        $rs['msg'] = '订单错误';
        return response()->json($rs);
    }


    public static function wechatUnifyOrder($data)
    {
        $payment = EasyWeChat::payment(); // 微信支付
        $result = $payment->order->unify([
            'body'         => '商城订单',
            'out_trade_no' => $data['code'],
            'trade_type'   => 'JSAPI',  // 必须为JSAPI
            'openid'       => $data['openid'], // 这里的openid为付款人的openid
            'total_fee'    => $data['total_price'], // 总价单位分
            'timeStamp' => time(),
            'notify_url' => config('app.url').'/wx/pay-notify',
        ]);
        Log::info('生成订单：'.json_encode($result));

        // 如果成功生成统一下单的订单，那么进行二次签名
        if ($result['return_code'] === 'SUCCESS') {
            // 二次签名的参数必须与下面相同
            $params = [
                'appId'     => config('wechat.mini_program.default.app_id'),
                'timeStamp' => time(),
                'nonceStr'  => $result['nonce_str'],
                'package'   => 'prepay_id=' . $result['prepay_id'],
                'signType'  => 'MD5',
            ];
            // config('wechat.payment.default.key')为商户的key
            $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
            $params['signJs'] = $result['sign'];
            $params['order_id']      = $data['order_id'];
            $params['order_code']    = $data['code'];
            $params['order_created'] = date('Y-m-d H:i:s');
            return $params;
        } else {
            $rs['param'] = $data;
            $rs['result'] = $result;
            return $rs;
        }
    }

    

   

    
}
